<template>
  <div class="panel">
    <div class="timeline">
      <div class="timeline-line"></div>
      <div
        v-for="(item, index) in traceData"
        :key="index"
        class="timeline-item"
        :class="{ 'top': index % 2 === 0, 'bottom': index % 2 !== 0 }"
        @click="toggleExpand(index)"
      >
        <div class="timeline-node"></div>
        <div class="timeline-content">
          <div class="basic-info">
            <span class="event-title">{{ item.event }}</span>
            <span class="operator">{{ item.location }}</span>
          </div>
        </div>
        <el-collapse-transition>
          <div v-show="expandedIndex === index" class="detail-popup" :class="{ 'left': index > traceData.length / 2 }">
            <div class="popup-content">
              <div class="popup-header">
                <span class="event-title">{{ item.event }}</span>
                <el-icon class="close-icon" @click.stop="expandedIndex = null"><Close /></el-icon>
              </div>
              <div class="info-item">
                <span class="label">地点：</span>
                <span class="value">{{ item.location }}</span>
              </div>
              <div class="info-item">
                <span class="label">证书编号：</span>
                <span class="value">{{ item.certificate }}</span>
              </div>
              <div class="info-item">
                <span class="label">质量信息：</span>
                <span class="value">{{ item.quality }}</span>
              </div>
              <div class="info-item">
                <span class="label">说明：</span>
                <span class="value">{{ item.description }}</span>
              </div>
              <div v-if="item.images.length > 0" class="image-container">
                <el-image
                  v-for="(img, imgIndex) in item.images"
                  :key="imgIndex"
                  :src="img"
                  :preview-src-list="[img]"
                  fit="cover"
                  class="product-image"
                />
              </div>
            </div>
          </div>
        </el-collapse-transition>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Close } from '@element-plus/icons-vue'
import type { TraceRecord } from '@/types/traceability'
import { traceabilityApi } from '@/api/traceability'

const expandedIndex = ref<number | null>(null)

const toggleExpand = (index: number) => {
  expandedIndex.value = expandedIndex.value === index ? null : index
}

// 时间线数据
const traceData = ref<{
  time: string
  event: string
  location: string
  description: string
  operator: string
  certificate: string
  quality: string
  images: string[]
}[]>([])

// 获取溯源数据并转换为时间线格式
const fetchTraceData = async () => {
  try {
    console.log('开始获取溯源数据用于时间线显示...')
    const response = await traceabilityApi.getAllTraceData()
    console.log('时间线溯源数据API响应:', response)

    if (response.data.code === 200) {
      console.log('时间线API返回成功，检查数据类型...')

      // 检查data是否为数组
      if (!Array.isArray(response.data.data)) {
        console.error('response.data.data不是数组:', {
          type: typeof response.data.data,
          value: response.data.data,
          response: response.data
        })
        console.log('使用模拟时间线数据作为后备')
        useMockTimelineData()
        return
      }

      console.log('时间线溯源数据获取成功，数据条数:', response.data.data.length)

      // 转换数据为时间线格式
      const timelineData = response.data.data.map((item: TraceRecord, index: number) => {
        // 根据processType确定事件名称
        let eventName = item.processName || `${item.processType}环节`

        // 生成证书编号
        const certificatePrefix = {
          planting: 'QDNK',
          growing: 'QDFL',
          harvest: 'QDCZ',
          processing: 'QDZJ',
          transport: 'QDYS',
          storage: 'QDCC',
          delivery: 'QDPS'
        }[item.processType] || 'QDXX'

        const certificate = `${certificatePrefix}${item.processTime.replace(/[-:]/g, '').slice(0, 8)}${String(index + 1).padStart(3, '0')}`

        // 生成质量信息
        let qualityInfo = '质量检测合格'
        if (item.status === 'unqualified') {
          qualityInfo = '质量检测不合格，需要重新处理'
        } else if (item.status === 'pending') {
          qualityInfo = '质量检测待处理'
        }

        return {
          time: item.processTime,
          event: eventName,
          location: item.location || '未知地点',
          description: item.description || `${eventName} - ${item.operator}`,
          operator: item.operator,
          certificate: certificate,
          quality: qualityInfo,
          images: [] // 暂时为空，后续可以添加图片功能
        }
      })

      traceData.value = timelineData
      console.log('时间线数据转换完成，条数:', timelineData.length)

      if (timelineData.length === 0) {
        console.warn('没有找到有效的时间线数据，使用模拟数据')
        useMockTimelineData()
      }
    } else {
      console.error('时间线溯源数据API返回错误:', {
        code: response.data.code,
        message: response.data.message,
        data: response.data.data
      })
      console.log('使用模拟时间线数据作为后备')
      useMockTimelineData()
    }
  } catch (error) {
    console.error('获取时间线溯源数据失败:', {
      error: error,
      message: error instanceof Error ? error.message : '未知错误',
      stack: error instanceof Error ? error.stack : undefined,
      timestamp: new Date().toISOString()
    })
    console.log('使用模拟时间线数据作为后备')
    useMockTimelineData()
  }
}

// 使用模拟时间线数据
const useMockTimelineData = () => {
  console.log('加载模拟时间线数据')
  traceData.value = [
    {
      time: '2024-04-15',
      event: '种植阶段',
      location: '山西省朔州市',
      description: '开始种植玉米',
      operator: '朔州窑子头村种植基地',
      certificate: '种植许可证：QDNK20240115001',
      quality: '土壤检测合格，PH值6.8',
      images: ['/src/assets/img/food/110_番茄.png']
    },
    {
      time: '2025-05-20',
      event: '灌溉阶段',
      location: '山西省朔州市',
      description: '第一次施肥',
      operator: '朔州窑子头村种植基地',
      certificate: '有机肥料认证：QDFL20240220001',
      quality: '使用有机肥料，符合GB/T 23349-2009标准',
      images: []
    },
    {
      time: '2025-06-10',
      event: '生长阶段',
      location: '山西省朔州市',
      description: '进行病虫害防治',
      operator: '朔州窑子头村种植基地',
      certificate: '农药使用许可证：QDNJ20240310001',
      quality: '使用生物农药，符合NY/T 393-2020标准',
      images: []
    },
    {
      time: '2025-10-05',
      event: '采收阶段',
      location: '山西省朔州市',
      description: '开始采摘',
      operator: '朔州窑子头村种植基地',
      certificate: '采摘许可证：QDCZ20240405001',
      quality: '采摘标准：果实成熟度≥85%，糖度≥6.5%',
      images: []
    },
    {
      time: '2025-04-10',
      event: '运输阶段',
      location: '山西省朔州市',
      description: '质量检测合格',
      operator: '朔州冷链物流有限公司',
      certificate: '质检报告：QDZJ20240410001',
      quality: '农残检测合格，重金属含量符合GB 2762-2022标准',
      images: []
    },
    {
      time: '2025-04-15',
      event: '仓储阶段',
      location: '山西省朔州市 → 北京市',
      description: '冷链运输至北京',
      operator: '朔州冷链物流有限公司',
      certificate: '运输许可证：QDYS20240415001',
      quality: '全程冷链，温度控制在0-4℃',
      images: []
    },
    {
      time: '2025-04-20',
      event: '销售阶段',
      location: '北京市',
      description: '进入超市销售',
      operator: '北京生鲜超市',
      certificate: '销售许可证：BJXS20240416001',
      quality: '符合GB/T 23349-2009标准',
      images: []
    }
  ]
  console.log('模拟时间线数据加载完成，条数:', traceData.value.length)
}

// 初始化
onMounted(async () => {
  await fetchTraceData()
})
</script>

<style scoped>
.panel {
  height: 100%;
  width: 100%;
  padding: 10px 20px;
  overflow-x: auto;
  display: flex;
  align-items: center;
  position: relative;
}

.timeline {
  position: relative;
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 60px 0;
  gap: 0;
  margin-left: 100px;
}

.timeline-line {
  position: absolute;
  top: 50%;
  left: 50px;
  right: 50px;
  height: 3px;
  background: linear-gradient(90deg,
    rgba(51, 255, 208, 0.2),
    rgba(51, 255, 208, 1) 5%,
    rgba(51, 255, 208, 1) 95%,
    rgba(51, 255, 208, 0.2)
  );
  transform: translateY(-50%);
  z-index: 1;
}

.timeline-item {
  position: relative;
  flex: 0 0 140px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0;
  min-width: 140px;
  margin: 0 -20px;
}

.timeline-node {
  width: 20px;
  height: 20px;
  border: 3px solid #33ffd0;
  border-radius: 50%;
  background: #33ffd0;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 4;
  box-shadow: 0 0 10px rgba(51, 255, 208, 0.5);
  transition: all 0.3s ease;
}

.timeline-item:hover .timeline-node {
  transform: translate(-50%, -50%) scale(1.2);
  box-shadow: 0 0 15px rgba(51, 255, 208, 0.8);
}

.timeline-item.top .timeline-content {
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  margin-bottom: 35px;
}

.timeline-item.bottom .timeline-content {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 35px;
}

.timeline-content {
  background: rgba(18, 161, 127, 0.1);
  border: 1px solid rgba(51, 255, 208, 0.2);
  backdrop-filter: blur(5px);
  border-radius: 4px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 180px;
  position: relative;
  z-index: 2;
}

.timeline-content::before {
  content: '';
  position: absolute;
  width: 2px;
  background: linear-gradient(
    to bottom,
    rgba(51, 255, 208, 0.3),
    rgba(51, 255, 208, 0.8)
  );
  left: 50%;
  transform: translateX(-50%);
}

.timeline-item.top .timeline-content::before {
  bottom: -35px;
  height: 35px;
}

.timeline-item.bottom .timeline-content::before {
  top: -35px;
  height: 35px;
  background: linear-gradient(
    to top,
    rgba(51, 255, 208, 0.3),
    rgba(51, 255, 208, 0.8)
  );
}

.timeline-content:hover {
  transform: translateX(-50%) scale(1.05);
  background: rgba(18, 161, 127, 0.2);
  border-color: rgba(51, 255, 208, 0.4);
  z-index: 3;
}

.basic-info {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.event-title {
  font-size: 16px;
  font-weight: bold;
  color: #33ffd0;
  text-align: center;
}

.operator {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
  text-align: center;
}

.detail-popup {
  position: absolute;
  z-index: 10;
  background: rgba(18, 161, 127, 0.8);
  border: 1px solid rgba(51, 255, 208, 0.4);
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(51, 255, 208, 0.3);
  backdrop-filter: blur(12px);
  width: 300px;
  max-height: 400px;
  overflow-y: auto;
  top: 50%;
  transform: translateY(-50%);
  left: calc(100% + 20px);
}

.detail-popup.left {
  left: auto;
  right: calc(100% + 20px);
}

.popup-content {
  padding: 16px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(51, 255, 208, 0.4);
}

.close-icon {
  cursor: pointer;
  color: #33ffd0;
  font-size: 20px;
  transition: all 0.3s ease;
}

.close-icon:hover {
  transform: scale(1.1);
  color: #fff;
}

.info-item {
  margin-bottom: 6px;
  display: flex;
  align-items: flex-start;
}

.label {
  color: #33ffd0;
  min-width: 70px;
  font-size: 13px;
}

.value {
  color: rgba(255, 255, 255, 0.9);
  font-size: 13px;
  flex: 1;
}

.image-container {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  border: 1px solid rgba(51, 255, 208, 0.2);
}

:deep(.el-collapse-transition) {
  transition: all 0.3s ease;
}

/* 自定义滚动条样式 */
.detail-popup {
  scrollbar-width: thin;
  scrollbar-color: rgba(51, 255, 208, 0.5) rgba(10, 43, 35, 0.2);
}

.detail-popup::-webkit-scrollbar {
  width: 6px;
}

.detail-popup::-webkit-scrollbar-track {
  background: rgba(10, 43, 35, 0.2);
  border-radius: 3px;
}

.detail-popup::-webkit-scrollbar-thumb {
  background: rgba(51, 255, 208, 0.5);
  border-radius: 3px;
}

.detail-popup::-webkit-scrollbar-thumb:hover {
  background: rgba(51, 255, 208, 0.8);
}

.operator {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
  text-align: center;
}
</style>
